package com.papercut.gui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.papercut.R;
import com.papercut.purchase.PurchaseActivity;
import com.papercut.purchase.PurchaseItem;
import com.papercut.service.RestService;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.provider.ContactsContract;
import android.telephony.TelephonyManager;
import android.text.Html;
import android.text.InputType;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

public class MoneySender extends Activity {
	
	private List<TextView> text_list = new ArrayList<TextView>();
	private TextView text;	
	private TextView money_box;
	private boolean selected = false;
	RestService mBoundService;
	private Context context;
	private Handler handler;


	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handler = new Handler();
        
		context = this;
		final Intent intent = new Intent(MoneySender.this,
				com.papercut.service.RestService.class);
		bindService(intent, new ServiceConnection() {

			public void onServiceConnected(
					ComponentName name, IBinder service) {
				Log.d("ASDFASDF", "Came into onServiceConnected");
				mBoundService = ((RestService.LocalBinder) service)
						.getService();
				if (mBoundService == null) {
					Log.d("ASDFASDFASDF", "mboundservice is null");
				}
				Log.d("ASDFASDF", "Came out of onServiceConnected");

			}

			public void onServiceDisconnected(
					ComponentName name) {
				Log.i("Activity",
						"on disconnect" + name.toString());

			}

		}, Context.BIND_AUTO_CREATE);
        
        
    	
    	text = new TextView(this);
    	
    	
    	LinearLayout money_sender_view = new LinearLayout(this);
    	money_sender_view.setOrientation(LinearLayout.VERTICAL);
    	money_sender_view.setBackgroundResource(R.drawable.amazon_background_swipecheck);
    	money_sender_view.setFocusable(true);
    	money_sender_view.setFocusableInTouchMode(true);
    	
    	TextView app_title = new TextView(this);
    	LinearLayout.LayoutParams app_title_layout = new LinearLayout.LayoutParams(
    				LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
    	
    	app_title_layout.setMargins(0, 20, 0, 10);
    	app_title.setText("Pay-Per-Cut");
    	app_title.setTextSize(24);
    	app_title.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
    	app_title.setTextColor(Color.rgb(231, 122, 0));
    	app_title.setGravity(Gravity.CENTER_HORIZONTAL);
    	money_sender_view.addView(app_title, app_title_layout);
    	
    	ScrollView scroll = new ScrollView(this);
		ViewGroup.LayoutParams scroll_layout = new ViewGroup.LayoutParams(480,400);

		LinearLayout scroll_linear = new LinearLayout(this);
		scroll_linear.setOrientation(LinearLayout.VERTICAL);
		
		
    	Uri something = ContactsContract.Contacts.CONTENT_URI; 
    	Cursor cursor = this.getContentResolver().query(something, null, null, null, null);
    	 //   	HashMap<String, String> phoneMap = new HashMap<String, String>(); use with phone numbers
    	    	List<String> people = new ArrayList<String>();

        while (cursor.moveToNext()) {
        	text = new TextView(this);
        	String hasNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
        	String contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
        	if (hasNumber.equals("1")) {
        		people.add(contactName);

    			text.setBackgroundColor(Color.rgb(240, 249, 255));
    			LinearLayout.LayoutParams text_layout = new LinearLayout.LayoutParams(
    						LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
    			
    			text_layout.setMargins(15, 0, 15, 0);
    			text.setText(contactName);
    		//	text.setText(Html.fromHtml("<font color=#001870>" + ": " + "</font> <font color=#E77A00>" + item.getTitle() + "</font>" + "<br />" +
    		//			"<font color=#001870>" + "Price: " + "</font> <font color=#E77A00>" + item.getPrice() + "</font>"));
    			text.setTextColor(Color.rgb(0, 24, 112));
    			text.setTextSize(24);
    			text.setGravity(Gravity.LEFT);
    			scroll_linear.addView(text, text_layout);
    			text_list.add(text);
    			text.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						for (TextView thing : text_list) {
							thing.setTypeface(Typeface.DEFAULT);
							thing.setTextColor(Color.rgb(0, 24, 112));
						}
						((TextView) arg0).setTypeface(Typeface.DEFAULT, Typeface.BOLD);
						((TextView) arg0).setTextColor(Color.rgb(231, 122, 0));
						selected = true;
						
					}
    				
    			});
    			
    			ImageView line = new ImageView(this);
    			LinearLayout.LayoutParams line_layout = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    			line_layout.setMargins(15, 0, 15, 0);
    			line.setImageResource(R.drawable.in_between_line);
    			scroll_linear.addView(line, line_layout);
        	}
        		
		}
		
		scroll.addView(scroll_linear);
		money_sender_view.addView(scroll, scroll_layout);    	

        money_box = new EditText(this);
        LinearLayout.LayoutParams money_box_layout = new LinearLayout.LayoutParams(
                        LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
        money_box_layout.setMargins(90, 60, 90, 0);
        money_box.setText("Enter $ Amount:");
        money_box.setTextSize(20);
        money_box.setMaxLines(1);
        money_box.setTextColor(Color.GRAY);
        money_box.setGravity(Gravity.CENTER_HORIZONTAL);
		money_box.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
		money_box.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        money_box.setOnFocusChangeListener(new OnFocusChangeListener() {

                @Override
                public void onFocusChange(View arg0, boolean has_focus) {
                        if (has_focus == true) {
                                money_box.setText("");
                                money_box.setTextColor(Color.BLACK);
                        }
                        
                }

        });
        money_sender_view.addView(money_box, money_box_layout);

        LinearLayout horizontal = new LinearLayout(this);
    	horizontal.setOrientation(LinearLayout.HORIZONTAL);
    	
    	ImageView small_save = new ImageView(this);
    	LinearLayout.LayoutParams small_save_layout = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    	small_save_layout.setMargins(42, 50, 15, 0);
    	small_save.setImageResource(R.drawable.small_save);
    	small_save.setOnClickListener(new OnClickListener() {
    		


    		@Override
    		public void onClick(View arg0) {
    			if (!money_box.getText().toString().equals("Enter $ Amount:")) {
    				if (money_box.getText().toString().length() > 0) {
    					if (selected) {
    						Intent verify_intent = new Intent(MoneySender.this, SwipeCheck.class);
    						startActivityForResult(verify_intent, 50);
    					}
    					else {
    		    			int duration = Toast.LENGTH_SHORT;
    						CharSequence text = "Missing Contact";

    		    			Toast toast = Toast.makeText(MoneySender.this, text, duration);
    		    			toast.show();

    					}
    				}
    				else {
		    			int duration = Toast.LENGTH_SHORT;
						CharSequence text = "Enter money amount.";

		    			Toast toast = Toast.makeText(MoneySender.this, text, duration);
		    			toast.show();
    				}
    			}
    			else {
	    			int duration = Toast.LENGTH_SHORT;
					CharSequence text = "Enter money amount.";

	    			Toast toast = Toast.makeText(MoneySender.this, text, duration);
	    			toast.show();
    			}
    		}
    		
    	});
    	horizontal.addView(small_save, small_save_layout);

    	ImageView cancel = new ImageView(this);
    	LinearLayout.LayoutParams cancel_layout = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    	cancel_layout.setMargins(15, 50, 15, 0);
    	cancel.setImageResource(R.drawable.cancel_small);
    	cancel.setOnClickListener(new OnClickListener() {

    		@Override
    		public void onClick(View v) {
    			CharSequence text = "Canceled money transfer.";
    			int duration = Toast.LENGTH_SHORT;

    			Toast toast = Toast.makeText(MoneySender.this, text, duration);
    			toast.show();
    			
    			finish();
    		}
    		
    	});
    	
    	horizontal.addView(cancel, cancel_layout);
    	
    	money_sender_view.addView(horizontal);
    	
    	setContentView(money_sender_view);

    }
    
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	super.onActivityResult(requestCode, resultCode, data);
    	ICallback callback = new ICallback() {

			@Override
			public void success(Object data) {
				handler.post(new Runnable () {
					public void run()
					{
						finish();
		    			/*int duration = Toast.LENGTH_SHORT;
						CharSequence text = "Successful";

		    			Toast toast = Toast.makeText(MoneySender.this, text, duration);
		    			toast.show();
						finish();
						//status_info.setText("Create new Swipe Key");
						//action_button.setImageResource(R.drawable.save_button);		
						//for (int x = 0; x < images.length; x++) {
						//	images[x].setImageResource(empty_node);
						//}
*/
					}
				});
			}

			@Override
			public void failure(String error) {
				handler.post(new Runnable () {
					public void run()
					{
						finish();
		    			/*int duration = Toast.LENGTH_SHORT;
						CharSequence text = "Successful";

		    			Toast toast = Toast.makeText(MoneySender.this, text, duration);
		    			toast.show();
						finish();
						//status_info.setText("Create new Swipe Key");
						//action_button.setImageResource(R.drawable.save_button);		
						//for (int x = 0; x < images.length; x++) {
						//	images[x].setImageResource(empty_node);
						//}
*/
					}
				});
			}
		};
		
		TelephonyManager telephone_manager = (TelephonyManager) this
		.getSystemService(Context.TELEPHONY_SERVICE);
		String phone_number_string = telephone_manager.getLine1Number();
if (phone_number_string == null) {
	phone_number_string = "12223334444";
}
final String deviceID = ((TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();


		Thread moneyThread = new Thread(new MoneySend(callback, deviceID, phone_number_string, money_box.getText().toString()));
		moneyThread.start();
    }
    
    private class MoneySend implements Runnable{
		private final ICallback callback;
		private final String money;
		private final String phone_number;
		private final String deviceID;
		
		public MoneySend(ICallback callback, String deviceID, String phone_number, String money){
			this.callback = callback;
			this.phone_number = phone_number;
			this.deviceID = deviceID;
			this.money = money;
		}
		
		@Override
		public void run() {
			boolean success = mBoundService.transferMoney(deviceID, phone_number, money);
			if(success){
				Log.d("asdfasdf", "Callback success");
				this.callback.success(success);
			}
			else{
				this.callback.failure(null);
			}
		}
		
	}
    
    
	
	

}
